//---------------------------------------------------------------------
//  This file is part of the Background Motion solution.
// 
//  Copyright (C) Mindscape (TM).  All rights reserved.
//  http://www.mindscape.co.nz
// 
//  THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//---------------------------------------------------------------------

using System;
using System.Web;

using Mindscape.BackgroundMotion.Website.Controllers;

namespace Mindscape.BackgroundMotion.Website.Infrastructure
{
  /// <summary>
  /// This module implements the custom authentication scheme used within Background Motion
  /// </summary>
  /// <remarks>
  /// This module ultimately calls down to the MembershipController.AuthenticateRequest
  /// Note: We chose not to use Forms authentication due to the complexity in abstracting away from it to allow for automated testing
  /// </remarks>
  public class CustomAuthModule : IHttpModule
  {
    /// <summary>
    /// Initializes a module and prepares it to handle requests.
    /// </summary>
    /// <param name="context">An <see cref="T:System.Web.HttpApplication"></see> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
    public void Init(HttpApplication context)
    {
      context.AcquireRequestState += new EventHandler(AcquireRequestStateEvent);
    }

    /// <summary>
    /// Acquires the request state event.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    private static void AcquireRequestStateEvent(object sender, EventArgs e)
    {
      if ((HttpContext.Current.Session == null)
        || HttpContext.Current.Request.Path.EndsWith(MembershipController.LoginPage))
      {
        return;
      }

      new MembershipController().AuthenticateRequest();
    }

    /// <summary>
    /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"></see>.
    /// </summary>
    public void Dispose()
    {
    }
  }
}